package com.yst.gateway.monitor.common.filters;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * 自定义HttpServletRequest，解决get取参乱码
 * @author sheungxin
 *
 */
public class GetHttpServletRequestWrapper extends HttpServletRequestWrapper{
	private String encoding;  
	  
    public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public GetHttpServletRequestWrapper(HttpServletRequest request) {  
        super(request);
    }  
  
    /** 
     * 获得被装饰对象的引用和采用的字符编码 
     * @param request 
     * @param charset 
     */  
    public GetHttpServletRequestWrapper(HttpServletRequest request,String encoding) {  
        super(request);  
        this.encoding = encoding;  
    }  
  
    /** 
     * 实际上就是调用被包装的请求对象的getParameter方法获得参数，然后再进行编码转换 
     */  
    public String getParameter(String name) {  
        String value = super.getParameter(name);  
        value = value == null ? null : convert(value);  
        return value;  
    }
  
    public String[] getParameterValues(String paramString){
    	String[] params=super.getParameterValues(paramString);
    	convertArray(params);
    	return params;
    }
    
    @SuppressWarnings("unchecked")
	public Map<String, String[]> getParameterMap(){
    	Map<String, String[]> paramMap=super.getParameterMap();
    	for(String key:paramMap.keySet()){
    		convertArray(paramMap.get(key));
    	}
    	return paramMap;
    }
    
    public String convert(String target) {
        try {
            return new String(target.trim().getBytes("ISO-8859-1"), encoding!=null?encoding:"UTF-8");  
        } catch (Exception e) {  
            return target;  
        }  
    }
    
    public void convertArray(String[] array){
    	if(array!=null&&array.length>0){
    		for(int i=0;i<array.length;i++){
    			array[i]=convert(array[i]);
    		}
    	}
    }

}
